import Vuex from 'vuex'
import Vue from 'vue'
import $http from '@/utils/http/api.js'
import {router} from '@/router/router.js'
import ShowToast from '@/components/ch-toast/ch-showtotast.js';
import imMsg from "@/utils/common/message.js";
import { decrypt, encrypt } from "@/utils/common/encrypt.js";

Vue.use(Vuex)

const getDefaultState = () => {
	return {
		user: {}, //用户信息
		userToken: null, //用户Token
		isLogin: false, //登录状态
		imReady: false, // TIM SDK 是否 ready
		chatId: null, //当前对话ID
		newMessage: 0, //新消息数量
		barNotice: 0, //球吧消息数量
		imageDomain: 'http://www.image.caihongsport.com',
		videoDomain: 'http://www.video.caihongsport.com',
		matchFollow: [[],[]],
		matchNoFollow: [[],[]],
		expertFollow: [],
		expertNoFollow: [],
		couponinfo:{coupinPrice:0,couponsId:null},
		weixin:false
	}
}
 
const state = getDefaultState()

const store = new Vuex.Store({
	state,
	mutations: {
		//初始化登录
		INIT_LOGIN: (state) => {
			console.log('INIT_LOGIN')
			//获取本地用户信息
			let user = uni.getStorageSync('user_info_enc') || null
			if(user){
				state.user = JSON.parse(decrypt(user))
			}
			let userToken = uni.getStorageSync('user_token_enc') || null
			if(userToken){
				state.userToken = decrypt(userToken)
			}
			if(state.user.imAppId && state.userToken){
				state.isLogin = true
				imMsg.init(state.user.imAppId)
				console.log('isLogin')
			}
			console.log(state.user);
			console.log(state.userToken);
		},
		//设置用户信息与登录状态
		SET_USERINFO(state, data={}) {
			if(data.userInfo && data.token){
				state.isLogin = true
				state.user = data.userInfo
				state.userToken = data.token
				uni.setStorageSync('user_token_enc', encrypt(data.token))
				uni.setStorageSync('user_info_enc', encrypt(JSON.stringify(data.userInfo)))
			}else{
				state.isLogin = false
				state.userToken = null
			}
		},
		//设置用户Token
		SET_USERTOKEN(state, token) {
			console.log(token,'state')
			if(token){
				state.userToken = token
				uni.setStorageSync('user_token_enc', encrypt(token))
			}else{
				state.userToken = null
			}
		},
		//更新用户信息
		UPDATE_USERINFO(state, data=null) {
			if(data){
				state.user = Object.assign({}, state.user, data)
				uni.setStorageSync('user_info_enc', encrypt(JSON.stringify(state.user)))
			}
			console.log(data,'用户信息')
		},
		//更新用户登录状态
		UPDATE_USERSTATUS: (state) => {
			state.isLogin = false
			state.userToken = null
			state.chatId = null
			uni.removeStorageSync('user_token_enc')
			uni.removeStorageSync('user_info_enc')
			if(state.imReady){
				imMsg.logout()
			}
		},
		//更新IMSDK状态
		UPDATE_IMSTATUS: (state, status) => {
			console.log('IM SDK Ready:', status);
			state.imReady = status
			if(status){
				//更新资料
				imMsg.updateMyProfile()
			}
		},
		//更新会话未读总数
		UPDATE_UNREADMSG: (state, num) => {
			state.newMessage = num
			if(state.newMessage > 0){
				let textNum = state.newMessage > 99 ? '99+' : state.newMessage.toString()
				uni.setTabBarBadge({
					index: 1,
					text: textNum
				})
			}else{
				uni.removeTabBarBadge({
					index: 1
				})
			}
		},
		//更新IM消息提醒
		UPDATE_NEWMSG: (state, data) => {
			if(state.isLogin){
				if(router.currentRoute.name != 'message' && data[0].conversationID != state.chatId){
					//新消息提醒
					ShowToast({text: '您有新的未读消息', go: true, chatId: data[0].conversationID, time: 2})
				}
			}
		},
		//更新球吧未读消息
		// UPDATE_BARNOTICE: (state, num) => {
		// 	state.barNotice = num
		// 	if(state.barNotice > 0){
		// 		let textNum = state.barNotice > 99 ? '99+' : state.barNotice.toString()
		// 		uni.setTabBarBadge({
		// 			index: 1,
		// 			text: textNum
		// 		})
		// 	}else{
		// 		uni.removeTabBarBadge({
		// 			index: 1
		// 		})
		// 	}
		// },
		//保存当前回话Id
		SET_CHATID: (state, chatId) => {
			state.chatId = chatId
		},
		//保存取消关注的比赛ID
		NO_FOLLOW_MATCH: (state, data) => {
			let index = state.matchFollow[data.sportId-1].indexOf(data.matchId)
			if(index > -1){
				state.matchFollow[data.sportId-1].splice(index, 1)
			}
			if(state.matchNoFollow[data.sportId-1].indexOf(data.matchId) == -1){
				state.matchNoFollow[data.sportId-1].push(data.matchId)
			}
		},
		//删除关注的比赛ID
		IS_FOLLOW_MATCH: (state, data) => {
			let index = state.matchNoFollow[data.sportId-1].indexOf(data.matchId)
			if(index > -1){
				state.matchNoFollow[data.sportId-1].splice(index, 1)
			}
			if(state.matchFollow[data.sportId-1].indexOf(data.matchId) == -1){
				state.matchFollow[data.sportId-1].push(data.matchId)
			}
		},
		//保存取消关注的专家ID
		NO_FOLLOW_EXPERT: (state, expertId) => {
			let index = state.expertFollow.indexOf(expertId)
			if(index > -1){
				state.expertFollow.splice(index, 1)
			}
			if(state.expertNoFollow.indexOf(expertId) == -1){
				state.expertNoFollow.push(expertId)
			}
		},
		//删除取消关注的专家ID
		IS_FOLLOW_EXPERT: (state, expertId) => {
			let index = state.expertNoFollow.indexOf(expertId)
			if(index > -1){
				state.expertNoFollow.splice(index, 1)
			}
			if(state.expertFollow.indexOf(expertId) == -1){
				state.expertFollow.push(expertId)
			}
		},
		//重置状态
		RESET_STATE: (state) => {
			Object.assign(state, getDefaultState())
		},
		USER_COUPON:(state,coupon)=>{
			console.log(coupon,'coupon')
			state.couponinfo=coupon
		},
		IS_WEIXIN:(state,isweixin)=>{
			console.log(isweixin,'isweixin')
			state.weixin=isweixin
		}
	},
	actions: {
		//更新用户信息
		updateUserinfo: ({commit, state}) => {
			return new Promise((resolve, reject) => {
				$http.get({
					url: '/api/appUser/queryUserInfoById',
					data: {
						userId: state.user.userId
					},
					noLoading: true,
					noCheck: true
				}).then(data => {
					console.log('user update', data);
					if(data.code == 401){
						//更新用户状态
						commit("UPDATE_USERSTATUS")
						reject(data)
					}else if(data.code == 200 && data.result != null){
						//更新用户信息
						commit("UPDATE_USERINFO", data.result)
						resolve(data.result)
					}else{
						reject(data)
					}
				}).catch((err) => {
					reject(err)
				})
			})
		},
		updateBarNotice: ({commit}) => {
			return new Promise((resolve) => {
				$http.get({
					url: '/api/notify/unread/count',
					noLoading: true
				}).then(data => {
					console.log('update bar notice');
					if(data.code == 401){
						//更新用户状态
						commit("UPDATE_USERSTATUS")
					}else if(data.code == 200 && data.result != null){
						//更新消息数量
						// commit("UPDATE_BARNOTICE", data.result)
						resolve(data.result)
					}
				}).catch((err) => {
					console.log(err)
				})
			})
		},
		//更新用户信息
		updateUserRenown: ({commit, state}) => {
			return new Promise((resolve, reject) => {
				$http.get({
					url: '/api/appUser/user/score',
					data: {
						userId: state.user.userId
					},
					noLoading: true,
					noCheck: true
				}).then(data => {
					console.log('update renown');
					if(data.code == 401){
						//更新用户状态
						commit("UPDATE_USERSTATUS")
						reject(data)
					}else if(data.code == 200 && data.result != null){
						//更新用户信息
						commit("UPDATE_USERINFO", {
							renown: data.result,
							userScore: data.result.score
						})
						resolve(data.result)
					}else{
						reject(data)
					}
				}).catch((err) => {
					reject(err)
				})
			})
		},
		//跳转登录
		redirectLogin: ({commit}) => {
			//更新用户状态
			commit("UPDATE_USERSTATUS");
			//检测是否需要跳转
			let route = router.currentRoute
			if(route.meta.noCheck !== true){
				if(route.meta.loginRedirect !== true){
					let redirectTo = {name: route.name, params: route.query}
					sessionStorage.setItem('redirectTo', JSON.stringify(redirectTo))
					if(route.query.inviteCode){
						if(!route.query.inviteType){//兼容旧版本
							route.query.inviteType = route.query.inviteCode.length == 7 ? 'expert' : 'user'
						}
						let path = '/user/login/'+Date.now()+'?inviteType='+route.query.inviteType+'&inviteCode=' + route.query.inviteCode
						router.replaceAll({ path })
					}else{
						router.replaceAll({ name: 'userlogin', params: {random: Date.now()} })
					}
				}else if(route.name != 'userlogin'){
					router.replaceAll({ name: 'userlogin', params: {random: Date.now()} })
				}
			}
		},
		//退出登录
		logOut: ({commit}) => {
			return new Promise((resolve, reject) => {
				$http.get({
					url: '/api/userLogout'
				}).then(data => {
					uni.removeStorageSync('user_token_enc')
					uni.removeStorageSync('user_info_enc')
					commit("SET_USERINFO", {})
					resolve(data)
				}).catch((err) => {
					console.log(err)
					reject(err)
				})
			})
		}
	}
})
export default store